<script setup lang='ts'>
import type { VxeGridProps } from 'vxe-table'

import { useGetInfoPage, useGetSearchFeild, useInfoDel } from '@fl/api/man-api/pricing-tool'
import { SearchForm, SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import { cloneDeep } from 'lodash-es'
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { initPage, initialState } from '../constant'
import CalcDetailEdit from './calc-detail-edit.vue'

const router = useRouter()
const { query } = useRoute()

const tablePage = ref(cloneDeep(initPage))
const state = ref(cloneDeep(initialState))
const showCfg = ref(false)
const rowData = ref('')
const searchParams = computed(() => (query?.calcCategoryId ?? ''))
const { data: searchItem } = useGetSearchFeild(searchParams)

function getCondition() {
    if (!searchItem.value?.length)
        return ''
    const target = cloneDeep(searchItem.value)
    target.forEach((v: any) => {
        if (state.value[v.title]) {
            v.paramValue = state.value[v.title]
        }
    })
    return JSON.stringify(target)
}

const params = computed(() => ({
    objQuery: {
        calcCategoryId: query?.calcCategoryId,
        searchCondition: getCondition(),
    },
    page: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
}))

const { data, isLoading, refetch } = useGetInfoPage(params)

const btns = [
    {
        label: '修改',
        text: true,
        value: 'edit',
    },
    {
        label: '删除',
        text: true,
        value: 'delete',
    },
]

const columns = computed(() => {
    if (!searchItem.value?.length) {
        return []
    }
    const target = cloneDeep(searchItem.value)

    return target.map((v: any) => {
        return {
            colProps: {
                span: 6,
            },
            label: v.title,
            prop: v.title,
        }
    })
})

// 动态配置查询条件
const gridOptions = reactive<VxeGridProps>({
    columns: computed(() => {
        const records = data.value?.records ?? []
        const idxCol = { title: '序号', type: 'seq', width: 70 }
        const operCol = { slots: { default: 'operate' }, title: '操作', width: 250 }
        if (!records.length) {
            return [idxCol, operCol]
        }
        const keys = Object.keys(records[0])
        const fields = keys.filter((v: any) => v !== 'id')
        const target = fields.map((field: any) => {
            return { field, title: field }
        })
        return [idxCol, ...target, operCol]
    }),
    height: 550,
    rowConfig: {
        keyField: 'id',
    },
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

function doAction(item: any, row: any) {
    switch (item.value) {
        case 'edit':
            doEdit(row)
            break
        case 'delete':
            doDel(row.id)
            break
        default:
            break
    }
}

function doEdit(row?: any) {
    rowData.value = row ?? ''
    showCfg.value = true
}

const { mutate } = useInfoDel()
function doDel(id: any) {
    mutate(id, {
        onSuccess: () => {
            afterSuccess()
        },
    })
}

function afterSuccess() {
    ElMessage({ message: '操作成功', type: 'success' })
    refetch()
}

function getData(val: any) {
    tablePage.value.currentPage = 1
    state.value = {
        ...val,
    }
}

function reset() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initPage)
}

function goToList() {
    router.push('/operations-pages/pricing-tool/calc-item')
}

watchEffect(() => {
    if (data.value) {
        tablePage.value.total = data.value.total
    }
})
</script>

<template>
    <el-button mb-20
               @click="goToList"
    >
        返回列表
    </el-button>

    <el-card class="mb-20">
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="查询"
                    class="mb-20"
                    @submit="getData"
                    @reset="reset"
        />
    </el-card>

    <el-card>
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     v-loading="isLoading"
                     :data="data?.records"
        >
            <template #toolbar_buttons>
                <el-button type="primary"
                           @click="doEdit()"
                >
                    + 新增
                </el-button>
            </template>

            <template #operate="{ row }">
                <div class="text-#dA0004 flex gap-15 justify-center">
                    <ButtonItem :btns="btns"
                                @btn-click="doAction($event, row)"
                    />
                </div>
            </template>
        </SearchTable>
    </el-card>

    <!-- 配置弹框 -->
    <CalcDetailEdit v-if="showCfg"
                    v-model="showCfg"
                    :data="rowData"
                    @on-success="refetch"
    />
</template>
